# -*- coding: utf-8 -*-
"""
此文件中定义了主窗口要调用的相关子窗口，包括：
策略回测
策略运行监控
策略指标编辑
数据管理器
下单界面
常用统计方法界面
登录界面
"""
from os import path
from PyQt5 import QtGui, QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QTableWidgetItem, QWidget
from PyQt5.uic import loadUi, loadUiType
import pickle
from dbhelper.box_db import DbHelper
from ui.wStrategyRunningMonitor import Ui_StrategyRunningMonitor
from ui.wBacktest import Ui_StrategyBacktest
from ui.wDataManager import Ui_DataManager
from ui.frameOrder import Ui_FrameOrder
from config.configpath import pyqt_ui_path
OrderForm, OrderBase = loadUiType(path.join(pyqt_ui_path,'frameOrder.ui'))
StStrategyBacktestForm, StrategyBacktestBase = loadUiType(path.join(pyqt_ui_path,'wBacktest.ui'))
StrategyRunningMonitorForm, StrategyRunningMonitorBase = loadUiType(path.join(pyqt_ui_path,'wStrategyRunningMonitor.ui'))
DataManagerForm, DataManagerBase = loadUiType(path.join(pyqt_ui_path,'wDataManager.ui'))


class OrderPad(OrderBase, Ui_FrameOrder):
    """下单面板"""

    def __init__(self):
        super(Ui_FrameOrder, self).__init__()
        self.setupUi(self)


class StatUi(QMainWindow):
    """常用统计方法界面"""

    def __init__(self, *args):
        super(StatUi, self).__init__(*args)
        loadUi('uiStat.ui', self)  #
        self.pbFileName.clicked.connect(self.slotFile)
        self.pbLoadData.clicked.connect(self.slotLoadData)

    def slotFile(self):
        fileName1, filetype = QFileDialog.getOpenFileName(self,
                                                          "选取文件",
                                                          r"E:\Quant\notebook",
                                                          "All Files (*);;Text Files (*.txt)")
        self.leFileName.setText(fileName1)

    def slotLoadData(self):
        if self.leFileName.text() == '':
            self.slotFile()

        with open(self.leFileName.text(), 'rb') as f:
            df = pickle.load(f)
            df.index.name = 'datetime'
            # print(df.columns.values)
            from tools.pandasModel import PandasModel
            mymodel = PandasModel(df)
            self.tableView.setModel(mymodel)

            # self.tableView.setModel(df)
            # self.datatable.setColumnCount(len(df.columns))
            # self.datatable.setRowCount(len(df.index))
            # print(len(df.columns),len(df.index))
            # for i in range(len(df.index)):
            #     for j in range(len(df.columns)):
            #         self.datatable.setItem(i, j, QTableWidgetItem(str(df.iget_value(i, j))))


"""
from ui.BoxQuant import Ui_MainWindow


class BoxQuant(QMainWindow, Ui_MainWindow):
    def __init__(self, *args):
        super(BoxQuant, self).__init__(*args)
        # loadUi('BoxQuant.ui',self)
        self.setupUi(self)
        self._adjust_dockwidget()
        self.register_action_event()

    def _adjust_dockwidget(self):
        cw = self.takeCentralWidget()
        del cw

        self.dwData.hide()
        nullwidget = QWidget(parent=self.dwAccount)
        self.dwAccount.setTitleBarWidget(nullwidget)
        nullwidget = QWidget(parent=self.dwOrder)
        self.dwOrder.setTitleBarWidget(nullwidget)
        self.splitDockWidget(self.dwTech, self.dwQuoteDetail, QtCore.Qt.Horizontal)
        self.splitDockWidget(self.dwQuoteDetail, self.dwQuoteTotal, QtCore.Qt.Vertical)
        self.splitDockWidget(self.dwTech, self.dwStrategy, QtCore.Qt.Vertical)
        self.dwStrategy.hide()
        self.twIndicator.clear()

    def register_action_event(self):
        # self.actLoginQuoteServer.triggered.connect(self.connect_quote_server)
        # self.actOpenAccount.triggered.connect(self.connect_trade_server)
        # self.twStrategy.itemDoubleClicked.connect(self.twStrategy_itemDoubleClicked)
        # self.tw_strategy_instance.cellDoubleClicked.connect(self.tw_strategy_instance_itemDoubleClicked)
        # self.pb_strategy_init.clicked.connect(self.pb_strategy_initClicked)
        # self.pb_strategy_start.clicked.connect(self.pb_strategy_startClicked)
        # self.pb_strategy_stop.clicked.connect(self.pb_strategy_stopClicked)
        # self.pb_strategy_param_save.clicked.connect(self.pb_strategy_param_saveClicked)
        self.actionData.changed.connect(self.actionDataChanged)
        self.actionStrategy.triggered.connect(self.actionStrategyChanged)

    def actionDataChanged(self):
        if self.actionData.isChecked():
            self.dwData.setVisible(True)
        else:
            self.dwData.hide()

    def actionStrategyChanged(self):
        print('actionStrategyChanged')
        if self.actionStrategy.isChecked():
            self.dwStrategy.setVisible(True)
            self.dwAccount.setVisible(False)
            self.dwOrder.setVisible(False)

        else:
            self.dwStrategy.setVisible(False)
            self.dwAccount.setVisible(True)
            self.dwOrder.setVisible(True)
"""


class UITT(QMainWindow):
    def __init__(self, *args):
        super(UITT, self).__init__(*args)
        self.dwQuoteList = QtWidgets.QDockWidget(parent=self)
        self.addDockWidget(QtCore.Qt.TopDockWidgetArea, self.dwQuoteList)
        loadUi('wQuoteList.ui', self.dwQuoteList)
        self.dwAccount = QtWidgets.QDockWidget(parent=self)
        self.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.dwAccount)
        loadUi('wStrategyRunningMonitor.ui', self.dwAccount)
        self.dwBacktest = QtWidgets.QDockWidget(parent=self)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dwBacktest)
        loadUi('wBacktest.ui', self.dwBacktest)
        self.dwBacktest.showMaximized()
        self.tabifyDockWidget(self.dwBacktest, self.dwAccount)
        # print(type(self.dwAccount.twStrategy))
        # print(self.dwAccount.__dict__)


class DataManager(DataManagerBase, Ui_DataManager):
    """数据管理器"""

    def __init__(self, db_client=None):
        super(DataManager, self).__init__()
        self.setupUi(self)  #
        if not db_client:
            self._db = DbHelper()
        else:
            self._db = db_client
        self.register_event()

    def _init_ui(self):
        """初始化 tree list combobox table"""

    def register_event(self):
        """注册窗口控件的相关事件"""


class StrategyRunningMonitor(StrategyRunningMonitorBase, Ui_StrategyRunningMonitor):
    """策略监控"""
    def __init__(self):
        super(StrategyRunningMonitor, self).__init__()
        self.setupUi(self)


class StrategyBacktest(StrategyBacktestBase, Ui_StrategyBacktest):
    """策略回测"""

    def __init__(self):
        super(StrategyBacktest, self).__init__()
        self.setupUi(self)


if __name__ == '__main__':
    import sys
    from PyQt5.QtWidgets import QApplication

    app = QApplication(sys.argv)
    window = StrategyRunningMonitor()  # DataManager()
    window.show()

    sys.exit(app.exec())
